// @ts-nocheck
/**
 * @Date: 2022-04-16 10:07:03
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-15 20:52:10
 * @FilePath: \weibo-api\controller\topicCtl.js
 * @Description: 评论数据处理
 */

const { Topic, User, Reply, AtRelation } = require("../model/index");
const { SuccessModel, ErrorModel } = require("../ResModel");
const { analysis } = require("../tools");
const xss = require("xss");
const REG_AT = /@(.+?)\s-\s(\w+?)\b/g;
//创建评论
const createTopic = async (ctx, next) => {
  const { blogId } = ctx.params;
  const { content } = ctx.request.body;
  const { id: userId } = ctx.session.userInfo;
  const newTopic = { blogId, content, userId };
  try {
    const result = await Topic.create(newTopic);
    ctx.body = new SuccessModel(result.dataValues);
  } catch (error) {
    console.error(error);
    ctx.throw(500, "评论失败！，请稍后重试" + error);
  }
};
//创建回复
const createReply = async (ctx, next) => {
  const { replyUserId: reply_userId, parantId, commentId, blogId } = ctx.params;
  let { content, type } = ctx.request.body;
  const { id: userId } = ctx.session.userInfo;
  //获取用户@的id列表
  const userIdList = analysis(content, REG_AT);
  content = xss(content);
  content = content.replace(REG_AT, (itemStr, nickName, atUserId) => {
    return `<a href="/personal/${atUserId}" class="replyAitem">@${nickName}</a>`;
  });

  let newReply = { userId, content, reply_userId };
  if (type == "reply" && parantId != -1) {
    newReply.parantId = parantId;
  }
  // if (type == "comment" && commentId != -1) {
  newReply.commentId = commentId;
  newReply.blogId = blogId;
  // }
  try {
    const result = await Reply.create(newReply);
    //创建 @ 关系
    if (type == "reply") {
      if (userIdList.length > 0) {
        await Promise.all(
          userIdList.map(async (userId) => {
            let res = await AtRelation.create({
              userId: userId,
              // ReplyId: newReply.parantId,
              ReplyId: result.dataValues.id,
            });
            return res.dataValues;
          }),
        );
      }
    } else if (type == "comment") {
      if (userIdList.length > 0) {
        await Promise.all(
          userIdList.map(async (userId) => {
            let res = await AtRelation.create({
              userId: reply_userId,
              commentId: newReply.commentId,
            });
            return res.dataValues;
          }),
        );
      }
    }
    ctx.body = new SuccessModel(result.dataValues);
  } catch (error) {
    console.error(error);
    ctx.throw(500, "评论失败！，请稍后重试" + error);
  }
};
//获取评论列表
const getTopicList = async (ctx, next) => {
  let { currentPage = 1, pageSize = 5 } = ctx.query;
  currentPage = parseInt(currentPage);
  pageSize = parseInt(pageSize);
  const { blogId } = ctx.params;
  // console.log("博客id时", blogId);
  const topicWhereOpt = { blogId: parseInt(blogId) };
  const res = await Topic.findAndCountAll({
    limit: pageSize, //每页条数
    offset: (currentPage - 1) * pageSize, //跳过条数
    order: [
      //根据回复数量最多排序
      // [{ model: Reply, as: "replies" }, "parentId", "DESC"],
      //根据回复最新排序
      [{ model: Reply, as: "replies" }, "id", "DESC"],
      ["id", "desc"],
    ],
    attributes: ["id", "blogId", "userId", "content", "createdAt"],
    where: topicWhereOpt,

    include: [
      {
        model: User,
        attributes: ["id", "userName", "nickName", "avatar"],
      },
      {
        model: Reply,
        attributes: [
          "id",
          "parantId",
          "blogId",
          "userId",
          "reply_userId",
          "content",
          "createdAt",
        ],
        include: [
          {
            model: User,
            attributes: ["id", "userName", "nickName", "avatar"],
          },
        ],
      },
    ],
  });
  const blogres = await Topic.findAndCountAll({
    where: topicWhereOpt,
  });
  const topicList = res.rows.map((row) => row.dataValues);
  ctx.body = new SuccessModel({
    count: blogres.count,
    topicList,
  });
};
//删除评论
const deleteComment = async (ctx, next) => {
  const { commentId } = ctx.params;
  const res = await Topic.destroy({
    where: { id: commentId },
  });
  // console.log(res);
  if (res > 0) {
    ctx.body = new SuccessModel();
  } else {
    ctx.body = new ErrorModel(500, `删除失败！`);
  }
};
module.exports = {
  createTopic,
  getTopicList,
  createReply,
  deleteComment,
};
